#include "crossplat_def.h"
#include "server_push_flow.h"
#include "MultiCHData.h"
#include "frame_utility.h"
CServerPushFlow::CServerPushFlow()
{
	m_frmBuf = NULL;
	m_bufSz  = 800<<10;
	m_reconnect_tm = 15000;
	m_connect_status = false;
	m_frmBuf =new uchar_t[m_bufSz];
}

CServerPushFlow::~CServerPushFlow()
{
	delete [] m_frmBuf;
}


int CServerPushFlow::StartPushFlow()
{
	m_dataThdID = Cross_CreateThread((cross_start_routine) PushFlowThread, (void *)this,NULL, SIZE_128KB);

	return 0;
}

int CServerPushFlow::StartReconnect()
{
	m_reconnectThdID = Cross_CreateThread((cross_start_routine) ReconnectThread, (void *)this,NULL, SIZE_128KB);
	return 0;
}

int CServerPushFlow::VideoPushProc()
{
	int ret = 0;
	int frame_size = 0;
	int try_cnt  = 3;
	int64_t frmTm = 0;
	int64_t cur_tm = 0;
	int64_t diff = 0;

	CMultiCHData* g_mulData = CMultiCHData::getSingleton();
	CFrmUtility frmTool;
	frmTool.Init(m_frmBuf);

	while (true)
	{

		if(!m_connect_status)
		{
			CrossSleep(1000);
		
			try_cnt  = 3;
			continue;
		}

		ret = g_mulData->FIFO_GET_FRAME(m_frmBuf,m_bufSz,0,m_clientID); 

		if(ret < 0)
		{
			CrossSleep(10);
			continue;
		}
		
		GetDvrCurTime(&cur_tm);
		frmTm = frmTool.GetFramePts();
		diff = cur_tm - frmTm;
	
		if(frmTool.GetFrameType()== IFrame && diff >= 10)
		{
			PrintTimeMs(frmTm,0,"IFrame ");
			TRACE("CH %d diff %lld \n",0,diff);
		}

		frame_size = ret;
		
		ret = SendRawData((char*)m_frmBuf,frame_size);

		if(ret < 0)
		{
			if(0 ==try_cnt--)
			{
				m_connect_status = false;
			}
			
			TRACE("send error ret %d .\n",ret);
		}
	};

	return 0;
}

int CServerPushFlow:: PushFlowThread(void *pParam)
{
	CServerPushFlow * pTask = (CServerPushFlow*)pParam;

	pTask->VideoPushProc();

	return 0;
}

 int CServerPushFlow::ReconnectThread(void *pParam)
{
	int ret = 0;
	CServerPushFlow * pTask = (CServerPushFlow* )pParam;

	while (true)
	{
		if(pTask->m_connect_status)
		{
			CrossSleep(3000);
			continue;
		}

		if(0 == pTask->Reconnect())
		{
			pTask->m_connect_status = true;
		}

		CrossSleep(pTask->m_reconnect_tm);
	}

	return ret;
}